package parser;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;

import data.Vocabulary;
import data.WordOccurrenceMap;

public class UniqueWordFilter
{
	private static final UniqueWordFilter instance =  new UniqueWordFilter();
	
	private UniqueWordFilter()
	{
		
	}
	
	public static UniqueWordFilter getInstance()
	{
		return instance;
	}
	
	public Vocabulary filter(Vocabulary vocabulary, Iterable<WordOccurrenceMap> wordOccurrenceMaps)
	{
		Vocabulary filteredVocabulary;
		LinkedList<String> words = new LinkedList<String>(vocabulary.getWords());
		Iterator<String> wordsItr = words.iterator();
		while (wordsItr.hasNext())
		{
			String word = wordsItr.next();
			int conteningWordMailNumberMin;
			if (word.length() <= 3)
			{
				conteningWordMailNumberMin = 4;
			}
			else
			{
				conteningWordMailNumberMin = 2;
			}
			
			int conteningWordMailNumber = 0;
			Iterator<WordOccurrenceMap> wordOccurrenceMapItr = wordOccurrenceMaps.iterator();
			while (wordOccurrenceMapItr.hasNext() && conteningWordMailNumber < conteningWordMailNumberMin)
			{
				WordOccurrenceMap wordOccurrenceMap = wordOccurrenceMapItr.next();
				if (wordOccurrenceMap.get(word) > 0)
				{
					conteningWordMailNumber++;
				}
			}
			if (conteningWordMailNumber < conteningWordMailNumberMin)
			{
				for (WordOccurrenceMap wordOccurrenceMap : wordOccurrenceMaps)
				{
					wordOccurrenceMap.remove(word);
				}
				wordsItr.remove();
			}
		}
		filteredVocabulary = new Vocabulary(new ArrayList<String>(words));
		return filteredVocabulary;
	}
}
